const apiUrl = import.meta.env.VITE_API_URL;
import { userStore } from '../stores/user';

// 封装常规请求函数
const request = {
    // 封装 fetch 作为基础请求函数
    fetch: async (url, options) => {
        return await fetch(`${apiUrl}${url}`, options)
            .then((res) => {
                // 关键功能：统一返回体读取，直接返回原始 JSON（包含 code/message/data），便于调用方按 resp.code/resp.data 使用
                return res.json().catch(() => ({ code: res.status, message: res.statusText, data: null }))
            })
            .then((res) => {
                // 关键功能：401 处理，清理本地用户状态
                if (res && res.code === 401) {
                    localStorage.removeItem('token');
                    const user = userStore();
                    user.clearUserInfo();
                }
                // 关键功能：透传后端返回结构，同时兼容旧代码（success字段）
                const success = res && res.code === 200;
                return {
                    success,
                    code: res && res.code,
                    message: (res && (res.message || res.error)) || '',
                    data: res && res.data
                };
            })
            .catch((error) => {
                // 关键功能：网络/解析错误统一返回结构
                return { success: false, code: -1, message: error.message || '未知错误', data: null };
            });
    },
    // 封装 GET 请求
    get: (url, data) => {
        const queryString = new URLSearchParams(data);
        return request.fetch(`${url}${data ? '?' + queryString.toString() : ''}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
        });
    },
    // 封装 POST 请求
    post: (url, data) => {
        return request.fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            },
            body: JSON.stringify(data)
        });
    },
    // 封装 PUT 请求
    put: (url, data) => {
        return request.fetch(url, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            },
            body: JSON.stringify(data)
        });
    },
    // 封装 DELETE 请求
    delete: (url, data) => {
        return request.fetch(url, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            },
            body: JSON.stringify(data)
        });
    },
    // 封装 upload 请求
    upload: (url, formData) => {
        return request.fetch(url, {
            method: 'POST',
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('token')
            },
            body: formData
        });
    }
};

export default request;
